﻿using System;
using System.Collections.Concurrent;
using GameFramework.common;
using UnityEngine;

namespace GameFramework.data
{
    public class DataManager:Singleton<DataManager>
    {
        public LoadSaveStrategy loadSaveStrategy = new LocalLoadSaveStrategy();
        private ConcurrentDictionary<string, IData> datas = new ConcurrentDictionary<string, IData>();

        public T getData<T>() where T:class,IData
        {
            var name = typeof(T).Name;
            if (!datas.ContainsKey(name))
            {
                return null;
            }

            var data = datas[name] as T;
            if (data == null)
            {
                return null;
            }

            return data;
        }
        
        public T getOrLoadData<T>() where T:class,IData,new()
        {
            var name = typeof(T).Name;
            if (!datas.ContainsKey(name))
            {
                lock (this)
                {
                    if (!datas.ContainsKey(name))
                    {
                        T load1 = loadSaveStrategy.load<T>();
                        if (load1 != null)
                        {
                            datas[name] = load1;
                        }

                    }
                }
            }

            var data = datas[name] as T;
            if (data == null)
            {
                return null;
            }

            return data;
        }
        
        // public bool addData(IData newData)
        // {
        //     if (newData.dataName() == null || newData.dataName().Equals(""))
        //     {
        //         throw new Exception("数据名不能为空："+newData.GetType().Name);
        //     }
        //
        //     return datas.TryAdd(newData.dataName(), newData);
        // }
        
        public void saveAllData()
        {
            foreach (IData data in datas.Values)
            {
                try
                {
                    loadSaveStrategy.save(data);
                }
                catch (Exception e)
                {
                   Debug.LogError(e);
                }

            }
        }
        
    }
}